package com.example.myapplication444

import android.content.Intent
import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

import cn.edu.sicnu.cardgame.CardMatchingGame

class GameActivity : AppCompatActivity() {

    private lateinit var game: CardMatchingGame
    private lateinit var tvScore: TextView
    private lateinit var grid: GridLayout

    private var highScore = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_game)

        highScore = intent.getIntExtra("highScore", 0)
        tvScore = findViewById(R.id.tvScore)
        grid = findViewById(R.id.gridCards)

        findViewById<Button>(R.id.btnRestart).setOnClickListener { startNewGame() }
        findViewById<Button>(R.id.btnExit).setOnClickListener { finish() }

        startNewGame()
    }

    private fun startNewGame() {
        game = CardMatchingGame(16)
        updateUI()
    }

    private fun updateUI() {
        tvScore.text = getString(R.string.score_format, game.score)
        grid.removeAllViews()

        // 计算每张牌的正方形尺寸
        val screenW = resources.displayMetrics.widthPixels
        val cardSize = (screenW - 12 * 5) / 4   // 留边距 6dp×2 + 间隙 6dp×3

        for (i in 0 until 16) {
            val card = game.cardAtIndex(i)
            val button = Button(this).apply {
                text = if (card.isChosen || card.isMatched) card.toString() else "?"
                textSize = 24f
                setPadding(0, 0, 0, 0)
                layoutParams = GridLayout.LayoutParams().apply {
                    width = cardSize
                    height = cardSize
                    setMargins(3, 3, 3, 3)
                }
                setOnClickListener {
                    game.chooseCardAtIndex(i)
                    updateUI()
                    if (game.score > highScore) {
                        highScore = game.score
                        setResult(RESULT_OK, Intent().putExtra("newHighScore", highScore))
                    }
                }
            }
            grid.addView(button)
        }
    }
}